<template>
  <div ref="echart"></div>
</template>

<script>
import * as echarts from "echarts";
export default {
  props: {
    //接收到两个参数：chartData(是对象，同时设置默认值)里面包含xData[]和series，isAxisChart(表示是否是折线图，boolean值，默认值为true)
    chartData: {
      type: Object,
      default() {
        return { 
          xData: [],
          series,
        };
      },
    },
    isAxisChart: {
      type: Boolean,
      default: true,
    },
  },

  watch: {
    chartData: {
      handler: function () {
        this.initChart();
      },
      //immediate: true,
      deep: true,
    },
  },

  computed: {
    //原来的options不存在，需要进行计算得到
    options() {
      return this.isAxisChart ? this.axisOption : this.normalOption;
    },
  },

  methods: {
    initChart() {
      this.initChartData();
      // 设置echarts表格了
      // 如果echart不为空，就是echart已经绑定了图标则直接更新eachart
      if (this.echart) {
        this.echart.setOption(this.options);
      } else {
        //基于准备好的dom，初始化echarts实例
        this.echart = echarts.init(this.$refs.echart);
        this.echart.setOption(this.options); 
      }
    },
    initChartData() {
      //是折线图或者柱状图
      if (this.isAxisChart) {
        this.axisOption.xAxis.data = this.chartData.xData;
        this.axisOption.series = this.chartData.series;
      } else {
        //饼状图
        this.normalOption.series = this.chartData.series;
      }
    },
  },

  data() {
    return {
      axisOption: {
        legend: {
          // 图例文字颜色
          textStyle: {
            color: "#333",
          },
        },
        grid: {
          left: "20%",
        },
        // 提示框
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category", // 类目轴
          data: [],
          axisLine: {
            lineStyle: {
              color: "#17b3a3",
            },
          },
          axisLabel: {
            interval: 0,
            color: "#333",
          },
        },
        yAxis: [
          {
            type: "value",
            axisLine: {
              lineStyle: {
                color: "#17b3a3",
              },
            },
          },
        ],
        color: [
          "#2ec7c9",
          "#b6a2de",
          "#5ab1ef",
          "#ffb980",
          "#d87a80",
          "#8d98b3",
        ],
        series: [],
      },
      normalOption: {
        tooltip: {
          trigger: "item",
        },
        color: [
          "#0f78f4",
          "#dd536b",
          "#9462e5",
          "#a6a6a6",
          "#e1bb22",
          "#39c362",
          "#3ed1cf",
        ],
        series: [],
      },
      echart: null,
    };
  },
};
</script>
